import { AutoComplete, Form, Input, InputNumber, Modal, Radio, TreeSelect, message } from 'antd';
import { useCallback, useEffect, useState } from 'react';

import appService from '@/api/services/appService';
import { useParams } from '@/router/hooks';
import useWindowWidth from '@/hooks/event/use-window-width';

export type PermissionModalProps = {
  formValue: Permission;
  title: string;
  show: boolean;
  row: number;
  onOk: VoidFunction;
  onCancel: VoidFunction;
};

export interface Permission {
  content: string;
  enable?: boolean;
  order?: number;
  row?: number;
}

export default function PermissionModal({
  title,
  show,
  row,
  formValue,
  onOk,
  onCancel,
}: PermissionModalProps) {
  const { id } = useParams();
  const [form] = Form.useForm();
  const { isPc } = useWindowWidth();

  useEffect(() => {
    form.setFieldsValue({ ...formValue });
  }, [formValue, form]);

  const submit = async () => {
    await form.validateFields();
    onOk && onOk(form.getFieldsValue(), row);
  };

  return (
    <Modal title={title} open={show} onOk={submit} onCancel={onCancel}>
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 24 }}
        layout="vertical"
        style={{ padding: isPc ? '20px' : '0px' }}
      >
        <Form.Item<Permission>
          label="内容"
          name="content"
          required
          rules={[
            { required: true, message: '请输入内容' },
            { min: 3, message: '内容至少3个字符' },
            { max: 30, message: '内容过长' },
          ]}
        >
          <Input.TextArea style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }} />
        </Form.Item>

        <Form.Item<Permission> label="回答" name="answer">
          <Input.TextArea style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }} />
        </Form.Item>

        <Form.Item<Permission>
          label="排序"
          name="order"
          required
          rules={[
            { required: true, message: '请输入排序值' },
            {
              validator: (_, value) => {
                if (!value || value <= 0) {
                  return Promise.reject('排序需大于 0');
                }
                if (!Number.isInteger(Number(value))) {
                  return Promise.reject('排序需为整数');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <InputNumber
            style={{ width: '100%', borderRadius: '6px', border: '1px solid #DBDBDC' }}
          />
        </Form.Item>

        <Form.Item<Permission> label="状态" name="enable" required>
          <Radio.Group>
            <Radio value={true}> 展示 </Radio>
            <Radio value={false}> 隐藏 </Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
}
